// Copyright (c) 2020 Presto Labs Pte. Ltd.
// Author: chunhui

#pragma once

#include <cmath>
#include <cstdint>
#include <limits>

namespace interval_feed {

class StdCalculator {
 public:
  StdCalculator() {
    sum_ = 0;
    sum2_ = 0;
    cnt_ = 0;
  }

  void Update(double price) {
    sum_ += price;
    sum2_ += price * price;
    ++cnt_;
  }

  double GetStd() const {
    if (cnt_ == 0) {
      return std::numeric_limits<double>::quiet_NaN();
    }
    double mean = sum_ / cnt_;
    double variance = sum2_ / cnt_ - mean * mean;
    // Avoid negative number due to floating error
    return variance > 0 ? std::sqrt(variance) : 0;
  }

  double GetMean() const {
    if (cnt_ == 0) {
      return std::numeric_limits<double>::quiet_NaN();
    }
    return sum_ / cnt_;
  }

 private:
  double sum_;
  double sum2_;
  int64_t cnt_;
};

}  // namespace interval_feed
